#!/usr/bin/env python
# coding: utf-8

"""
Created on 02/11/2011

@autor Alfredo Campuzano
"""

class BNF:
    """Representation of a Backus-Naur form(BNF) grammar"""

    def __init__(self):
        self.non_terminals = []
        self.initial_symbol = None
        self.productions = []

    def add_production(self, non_terminal, production):
        """Adds a production for a non_terminal symbol."""
        
        if not non_terminal in self.non_terminals:
            self.non_terminals.append(non_terminal)
            self.productions.append([production])
        else:
            index = self.non_terminals.index(non_terminal)
            self.productions[index].append(production)

    def add_non_terminal(self, non_terminal):
        """Adds a non terminal symbol"""
        
        if not non_terminal in self.non_terminals:
            self.non_terminals.append(non_terminal)
            self.productions.append([])

    def set_initial_symbol(self, non_terminal):
        """Sets the initial non terminal symbol"""
        
        self.initial_symbol = non_terminal

    def __str__(self):
        
        result = "Initial Symbol: " + str(self.initial_symbol)
        result += "\n\nProductions:"
        non_terminals = self.non_terminals[::]
        non_terminals.sort()        
        for non_terminal in non_terminals:
            index = self.non_terminals.index(non_terminal)

            result += "\n" + str(non_terminal) + " -> "
            for production in self.productions[index]:
                result += str(production) + " | "
            result = result[0:-3]
        return result


